﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Net;
using System.Net.Mime;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using JXT.PrimaryKey.Batman.Log;

namespace JXT.PrimaryKey.Batman.Core.WcfService
{
    public abstract class WebHttpServiceErrorHandlerBase : IErrorHandler {
        public bool HandleError(Exception error) {
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault) {
            if (Logger != null)
            {
                Logger.Write(error.Message, error);
            }
            //MemoryStream ms = new MemoryStream();
            //XmlSerializer xs = new XmlSerializer(typeof(Error));
            WebHttpError webError = new WebHttpError();
            webError.Message = error.Message;
            if (error is WebHttpException)
            {
                WebHttpException e = error as WebHttpException;
                webError.Code = (byte)e.ErrorCode;
                webError.Status = (byte)e.StatusCode;
            }
            else if (error is System.Data.Common.DbException)
            {
                webError.Code = (byte)WebHttpErrorCode.Unknown;
                webError.Status = (int)HttpStatusCode.InternalServerError;
#if !DEBUG
                webError.Message = "服务出现未知错误,请与管理员联系.";
#endif
            }
            else
            {
                webError.Code = (byte)WebHttpErrorCode.Unknown;
                webError.Status = (int)HttpStatusCode.InternalServerError;
            }
            //xs.Serialize(ms, webError);
            //ms.Seek(0, SeekOrigin.Begin);
            //WebOperationContext.Current.OutgoingResponse.ContentType = MediaTypeNames.Text.Xml;
            //fault = Message.CreateMessage(
            //    MessageVersion.None,
            //    null,
            //    XmlReader.Create(ms));
            //WebOperationContext.Current.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode)webError.Status;
            //fault = WebOperationContext.Current.CreateXmlResponse<WebHttpError>(webError);
            fault = CreateFaultMessage(webError);
            //fault.UpdateHttpProperty();
        }

        protected abstract Message CreateFaultMessage(WebHttpError error);

        private ILogger _logger;

        protected virtual ILogger Logger
        {
            get
            {
                if (_logger == null)
                {
                    _logger = JXT.PrimaryKey.Batman.Container.ContainerManager.Default.Resolve<ILogger>();
                }
                return _logger;
            }
        }
    }
}
